<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, nextTick, onUnmounted, getCurrentInstance } from "vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { getLunar } from "chinese-lunar-calendar";
import {
  queryWeatherData,
  getFabZone,
  getReadersInZone,
  getPointNewValue,
  getPointsCurve,
  addRemake,
  remakeHistory,
  queryChildByTypeCodeAndItemValue,
  queryAreaWornings
} from "@/api/machineClass";
import { spcquerySpcAnalysis } from "@/api/spc";
import { PxMessage } from "px-ui";
import lineChart from "./lineChart.vue";
import { queryById } from "@/api/message";
import { ArrowLeft } from "@px-ui/icons-vue";
import * as echarts from "echarts";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import { useRouter } from "vue-router";

const router = useRouter();

const { proxy }: any = getCurrentInstance();

const currentTime = ref("");
const currentDate = ref("");
const currentDay = ref("");

const activeIndex = ref(0);

const spcChartRef = ref<HTMLDivElement | null>(null);
const spcChartRefDom = ref(null);
const spcChartWeatherRef = ref(null);
let chartsInstance = null;
let chartsInstance1 = null;

const loading = ref(false);
const filterList = ref([
  {
    value: "LL",
    label: "低"
  },
  {
    value: "MM",
    label: "中"
  },
  {
    value: "HH",
    label: "高"
  }
]);
const typeList = ref([
  {
    value: "hour",
    label: "小时"
  }
]);
const testCompanyList = ref([
  {
    value: 4,
    label: "近4小时"
  },
  {
    value: 8,
    label: "近8小时"
  },
  {
    value: 16,
    label: "近16小时"
  }
]);

const minitesList = ref([
  {
    value: 10,
    label: "10分钟"
  },
  {
    value: 20,
    label: "20分钟"
  },
  {
    value: 30,
    label: "30分钟"
  }
]);

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const minY1 = ref(0);
const maxY1 = ref(100);
const minY2 = ref(0);
const maxY2 = ref(200);
const minY3 = ref(0);
const maxY3 = ref(300);

const total = ref(0);
const searchId = ref("");
const searchIdAlarm = ref("");
const yAxisVisible = ref(false);

const showAlarmDetail = ref(false);
const showSpcDetail = ref(false);
const alarmDetailList = ref([]);
const alarmDetailLoading = ref(false);

const emits = defineEmits(["hideHistory"]);

const state = reactive<any>({
  weatherForm: {
    num: "",
    type: "hour"
  },
  popoverData: {},
  // currentBackgroundImage: "",
  pointsData: [],
  pointsCurve: [],
  factoryList: [],
  areaData: [],
  dateRange: [],
  dateRangeSpc: [],
  dateRangeAlarm: [],
  checkList: [],
  spcDataList: [],
  spcOptionList: [],
  dataDetailTable: [],
  weatherOptions: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10
    // lifecycle: 4
  },
  queryAlarmParams: {
    pageNum: 1,
    pageSize: 10
  },
  Detail: {
    testCompany: 4
  },
  weatherData: {},
  spcJobList: [],
  weatherSpcJobList: [],
  tableData: [],
  tableAlarmData: [],
  tableAlarmSelectedData: [],
  tableAlarmDataAll: [],
  spcForm: {},
  querySpcDetailParams: {},
  alarmOptions: {},
  queryParams2: {
    pageNum: 1,
    pageSize: 10
  }
});

const lineBegin = ref("");
const lineWidth = ref(10);

const {
  popoverData,
  weatherForm,
  spcJobList,
  weatherSpcJobList,
  pointsData,
  pointsCurve,
  factoryList,
  areaData,
  spcDataList,
  spcOptionList,
  dataDetailTable,
  currentBackgroundImage,
  weatherOptions,
  queryParams,
  tableData,
  tableAlarmData,
  tableAlarmSelectedData,
  tableAlarmDataAll,
  dateRange,
  dateRangeSpc,
  dateRangeAlarm,
  querySpcDetailParams,
  checkList,
  Detail,
  queryAlarmParams,
  weatherData,
  spcForm,
  alarmOptions,
  queryParams2
} = toRefs(state);

const showDetails = ref<boolean>(false);

const pointClick = (row: any) => {
  popoverData.value = row;
};

const handleBtnClick = (row: any) => {
  const id = searchId.value;
  searchIdAlarm.value = id;
  queryAllAlarm(null);
  showDetails.value = true;
  showAlarmDetail.value = true;
  // initSpc1();
};

const handleQuerySpc = (val: number) => {
  if (val) {
    dateRangeSpc.value = initDate(val);
  }
};

const dateArr = ref([]);
const handleChangeLine = (val: number) => {
  if (!lineBegin.value) {
    PxMessage({
      message: "请选择开始时间",
      type: "warning"
    });
    lineWidth.value = null;
    return;
  }
  console.log(new Date(lineBegin.value), "66666666666");
  if (val) {
    dateArr.value = initLineDate(val);
    console.log(lineBegin.value, dateArr.value, "66666666666");
  }
};

const initLineTime = () => {
  lineBegin.value = proxy.parseTime(new Date().getTime() - 10 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}");
  lineWidth.value = 10;
  dateArr.value = initLineDate(lineWidth.value);
};

const getUnit = (val: any) => {
  const unitList = [
    {
      unitName: "celsius",
      unitValue: "℃"
    },
    {
      unitName: "percentage",
      unitValue: "%"
    },
    {
      unitName: "percentage",
      unitValue: "%"
    }
  ];
  if (val) {
  }
  return "";
};

// 日期转化
const initLineDate = (val: number) => {
  const start = proxy.parseTime(new Date(lineBegin.value).getTime(), "{y}-{m}-{d} {h}:{i}:{s}");
  const end = proxy.parseTime(new Date(lineBegin.value).getTime() + val * 60 * 1000 - 1, "{y}-{m}-{d} {h}:{i}:{s}");
  return [start, end];
};

const gotoSpc = () => {
  router.push({ path: "/machine/spc/spcseetings" });
};

const handleChange = (val: number) => {
  if (val) {
    dateRange.value = initDate(val);
  }
};

const handleChangeAlarm = (val: number) => {
  if (val) {
    dateRangeAlarm.value = initDate(val);
  }
};

// 查询
const handleQuery = async () => {
  getPointsChart(positionList.value);
  // addData();
};

/** 重置按钮操作 */
function resetQuery() {
  dateRangeSpc.value = initDate(4);
  Detail.value.testCompany = 4;
  handleQuery();
}

// 曲线详情
const handleComfim = (row: any) => {
  showAlarmDetail.value = true;
};

const getWeatherData = async () => {
  const params: any = { diffHours: weatherForm.value.num || 0 };
  const data = await queryWeatherData(params);
  weatherData.value = data;
};

// const tabsClick = (item, index, event) => {
//   console.log(
//     areaData.value.find(el => el.code === item.code),
//     "777777777777777"
//   );
//   const codeList = [
//     "AREA_3b14bf",
//     "AREA_6e4500",
//     "AREA_38b7aa",
//     "AREA_79e774",
//     "AREA_b69930",
//     "AREA_c3b151",
//     "AREA_dc46ef",
//     "AREA_ec4ebb",
//     "AREA_f796cf",
//     "ROOM_7b09b7"
//   ];
//   currentBackgroundImage.value =
//     areaData.value.find(el => el.code === item.code) && codeList.indexOf(item.code) !== -1
//       ? new URL(`../../../../../assets/images/machine/${item.code}.png`, import.meta.url).href
//       : new URL(`../../../../../assets/images/machine/AREA_6e4500.png`, import.meta.url).href;
//   activeIndex.value = index;
//   searchId.value = item.code;
//   queryTable();
//   queryPointsList();
// };

const turnBack = () => {
  emits("hideHistory");
  showDetails.value = false;
  showAlarmDetail.value = false;
  showSpcDetail.value = false;
};

const viewSpcDetail = () => {
  showDetails.value = true;
  showSpcDetail.value = true;
  dateRangeSpcDetail.value = initSpcDate();
  querySpc();
};

const positionList = ref([]);
// 获取点位列表
const queryPointsList = async () => {
  let arr = [];
  const data = await getReadersInZone({ code: searchId.value, facCode: factoryList.value[0].facCode, className: factoryList.value[0].className });
  // pointsData.value = data || [];
  arr = data.map((item: any) => {
    return item.positionNum;
  });
  positionList.value = arr;
  getPointValue(positionList.value, data);
  getPointsChart(positionList.value);
};

const xData = ref([]);
const yAxis = ref([]);
const legendData = ref([]);
const seriesData = ref([]);
// 获取点位曲线
const getPointsChart = async (arr: any) => {
  const data: any = await getPointsCurve({
    pointList: [...arr],
    startTime: dateRangeSpc.value[0],
    endTime: dateRangeSpc.value[1],
    timePeriod: "minutes"
  });
  const showData = data && data.slice(0, 2);
  pointsCurve.value =
    data &&
    data.map((item: any) => {
      return {
        spcForm: {
          minY: Math.floor(item.pointValueCurve.map((el: any) => el.num).sort((a: any, b: any) => a - b)[0] / 10) * 10, // 取最小值
          maxY: Math.ceil(item.pointValueCurve.map((el: any) => el.num).sort((a: any, b: any) => b - a)[0] / 10) * 10 // 取最大值
        },
        visible: false,
        ...item
      };
    });
  editBtns.value = pointsCurve.value.slice(0, 2);
  xData.value = showData[0]?.pointValueCurve.map(item => item.name);
  yAxis.value = showData.map((item, index) => {
    return {
      type: "value",
      name: `℃-Y${index + 1}`,
      offset: (0 + index) * 50,
      alignTicks: true,
      splitNumber: 5,
      axisLine: {
        lineStyle: {
          width: 2
        }
      }
    };
  });
  legendData.value = showData.map(item => item.pointName);
  checkList.value = showData.map(item => item.pointName);
  seriesData.value = showData.map((item, index) => {
    return {
      name: item.pointName,
      type: "line",
      yAxisIndex: index,
      emphasis: {
        focus: "series",
        blurScope: "coordinateSystem"
      },
      data: item.pointValueCurve.map(item => item.num)
    };
  });
  initSpc();
  window.addEventListener("resize", handelResize);
  // console.log(data, pointsCurve.value, xData.value, yAxis.value, legendData.value, seriesData.value, "=======================");
};

// 筛选出选中的项
const filterData = (arr1, arr2) => {
  for (let i = 0; i < arr2.length; i++) {
    if (!arr1.includes(arr2[i].pointName)) {
      arr2.splice(i, 1);
      return arr2;
    }
  }
  return arr2;
};

const editBtns = ref([]);

// 多选
const checkChange = val => {
  // chartsInstance.clear();
  // getPointsChart(val);
  let chartsData = pointsCurve.value;
  let filterData = chartsData
    .map((item, index) => {
      for (let i of val) {
        console.log(i);
        if (item.pointName === i) {
          return item;
        }
      }
    })
    .filter(item => item);
  editBtns.value = filterData;
  let lengds = val;
  let yAxis = filterData.map((item, index) => {
    return {
      type: "value",
      name: `℃-Y${index + 1}`,
      offset: (0 + index) * 50,
      alignTicks: true,
      splitNumber: 5,
      axisLine: {
        lineStyle: {
          width: 2
        }
      }
    };
  });
  let series =
    filterData &&
    filterData.map((item, index) => {
      return {
        name: item.pointName,
        type: "line",
        yAxisIndex: index,
        data: item.pointValueCurve.map(item => item.num)
      };
    });
  console.log(lengds, yAxis, series, "8888888888888888888888888");
  updateOption(lengds, yAxis, series);
};

// 获取点位实时数据(最大值、最小值、平均值)
const getPointValue = async (arr: any, data: any) => {
  const res: any = await getPointNewValue({
    panelCode: "points_stat",
    criteria: {
      points: [...arr],
      startTime: dateRangeSpc.value[0],
      endTime: dateRangeSpc.value[1]
    }
  });
  let pointList = data;
  pointList.forEach((item: any) => {
    res.rows.forEach((el: any) => {
      if (item.positionNum === el.point) {
        Object.assign(item, el);
      }
    });
  });
  pointsData.value = pointList || [];
};

const handleAreaChange = (val: any) => {
  // queryParams.value[`${val.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] = val;
};

// 获取区域列表
const queryAreaList = async (id: string) => {
  const data: any = await getFabZone({ id });
  data.forEach((item: any) => {
    getWorningNum(item.code);
  });
  areaData.value = data;
  searchId.value = areaData.value[activeIndex.value].code; // 默认查询选中的区域
};

// 根据区域获取报警信息
const getWorningNum = async (id: string) => {
  const params = {
    // areaId: id, // id 暂时写死联调
    // roomId: "ROOM_b20032", // id 暂时写死联调
    pageNum: 1,
    pageSize: 999
  };
  params[`${id.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] = id.indexOf("ROOM") === -1 ? [id] : id;
  const res: any = await queryAreaWornings(params);
  areaData.value.map((item: any) => {
    if (item.code === id) {
      item.worningNum = res?.data.length;
    }
    return item;
  });
};

// 查询报警明细
const querySpc = async () => {
  // const cwData = await queryChildByTypeCodeAndItemValue({
  //   value: "CWConfig",
  //   typeCode: "MCTS"
  // });
  // spcDataList.value = cwData ? cwData : [];
  // const jobIDs = [];
  // spcDataList.value.forEach((item: any) => {
  //   jobIDs.push(JSON.parse(item.itemDesc).spc_job);
  // });
  const params = {
    jobIdList: [...spcJobList.value],
    timePeriod: "hour",
    startTime: dateRangeSpcDetail.value[0] + " 00:00:00",
    endTime: dateRangeSpcDetail.value[1] + " 23:59:59"
  };
  const res: any = await spcquerySpcAnalysis(params);
  // 需要展示的SPC 可替换下方jobIdS
  // const showSpcIds = [
  //   "weather.outdoor.temp.dry_1",
  //   "SPC_QA_CWConfig11",
  //   "SPC_QA_CWConfig12",
  //   "SPC_QA_CWConfig1",
  //   "SPC_QA_CWConfig2",
  //   "SPC_QA_CWConfig3",
  //   "SPC_QA_CWConfig4",
  //   "SPC_QA_CWConfig7",
  //   "SPC_QA_CWConfig8"
  // ];
  // 过滤
  // const arr = res.filter((item: any) => jobIDs.indexOf(item.jobId) !== -1 && item.pointValues && item.pointValues.length > 0); // 过滤出有数据的
  const arr = res.filter((item: any) => spcJobList.value.indexOf(item.jobId) !== -1); // 过滤出有数据的
  const spcList = arr.map((item: any) => {
    item.startTime = dateRangeSpcDetail.value[0];
    item.endTime = dateRangeSpcDetail.value[1];
    item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
    return {
      ...item
    };
  });
  dataDetailTable.value = spcList;
  const obj = spcList[0];
  // weatherOptions.value = obj;

  const yAxis =
    spcList &&
    spcList.map((item, index) => {
      return {
        type: "value",
        name: obj.indicatorName,
        nameLocation: "middle", //居中
        offset: (0 + index) * 50,
        nameGap: 70, //轴线距离
        nameRotate: 90, //字体选择角度
        axisLine: {
          show: true,
          lineStyle: {
            type: "solid"
          }
        }
      };
    });
  const series =
    spcList &&
    spcList.map((obj, ind) => {
      return {
        // data: [400, 400, 400, 400, 400, 400],
        data: obj && obj.pointValues.length > 0 ? obj.pointValues.map(item => item.value) : [],
        type: "line",
        name: obj.indicatorName,
        yAxisIndex: ind,
        // areaStyle: {
        //   opacity: 0.15
        // },
        symbol: "none",
        markLine: {
          symbol: "none",
          data: [
            {
              name: "USL值",
              yAxis: Number(obj.uslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `USL值${obj.uslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            },
            {
              name: "UCL值",
              yAxis: Number(obj.uclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UCL值${obj.uclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "UWL值",
              yAxis: Number(obj.uwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UWL值${obj.uwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "Target值",
              yAxis: Number(obj.targetValue),
              lineStyle: {
                color: "#00E272",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `Target值${obj.targetValue}`,
                color: "#00E272",
                fontWeight: 600
              }
            },
            {
              name: "LWL值",
              yAxis: Number(obj.lwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LWL值${obj.lwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "LCL值",
              yAxis: Number(obj.lclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LCL值${obj.lclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "LSL值",
              yAxis: Number(obj.lslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `LSL值${obj.lslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            }
          ]
        }
      };
    });
  const legendData = spcList && spcList.map(item => item.indicatorName);
  const option = {
    color: "#ccc",
    grid: {
      left: "60px",
      top: "40px",
      right: "100px",
      bottom: "5%",
      containLabel: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data:
        obj && obj.pointValues.length > 0
          ? obj.pointValues.map(item => formatDate(item.time))
          : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: yAxis,
    series: series
  };
  weatherOptions.value = option;
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

const dateRangeSpcDetail = ref([]);

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let hour = date.getHours() < 10 ? "0" + date.getHours().toString() : date.getHours().toString();
  let minites = date.getMinutes() < 10 ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
  let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${year}-${month}-${da}`, `${year}-${month}-${da}`]; // 近一年时间范围
  // return [`${year}-${month}-${lastda} 00:00:00`, `${year}-${month}-${da} ${hour}:${minites}:${seconds}`]; // 近一年时间范围
};
// 重置筛选条件
const resetSpc = async () => {
  dateRangeSpcDetail.value = initSpcDate();
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  querySpc();
};
// 查询报警明细
const queryTable = async () => {
  const params = { ...queryParams.value };
  params[`${searchId.value.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] =
    searchId.value.indexOf("ROOM") === -1 ? [searchId.value] : searchId.value;
  const param = proxy.addDateRange(params, dateRange.value, "startTime", "endTime");
  const res: any = await queryAreaWornings(param);
  tableData.value = res?.data || [];
  total.value = res?.total || 0;
};

// 重置筛选条件
const resetTable = async () => {
  dateRange.value = [];
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  };
  searchId.value = areaData.value[activeIndex.value].code; // 重置为当前选中的区域
  queryTable();
};

const contentVisible = ref(false);
const contentTextVisible = ref(false);
const chosedAlarm = ref("");
const alarmRemake = ref("");
const viewAlarm = ref("");
const contentList = ref([]);
const total2 = ref(0);
const hishoryLoading = ref(false);

const getcontentList = row => {
  viewAlarm.value = row ? "alarm_" + row.alarmId : "";
  contentVisible.value = true;
  queryAlarmHistory();
};

const queryAlarmHistory = async () => {
  hishoryLoading.value = true;
  const res: any = await remakeHistory({
    businessKey: viewAlarm.value,
    ...queryParams2.value
  });
  contentList.value = res?.data || [];
  total2.value = res?.total || 0;
  hishoryLoading.value = false;
};

const addAlarmRemake = (row: any) => {
  chosedAlarm.value = "alarm_" + row.alarmId;
  alarmRemake.value = "";
  contentTextVisible.value = true;
};

const addcontent = () => {
  addRemake({
    businessKey: chosedAlarm.value,
    content: alarmRemake.value
  }).then(res => {
    PxMessage({
      message: "批注成功",
      type: "success"
    });
    contentTextVisible.value = false;
  });
};

// 报警批注
const alarmRemakeConfirm = async () => {
  const res = await addRemake({ businessKey: "", content: "" });
};

const tableRef = ref(null);

const clearTableSelection = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};

const selectIds = ref([]);
/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  const ids = selection.map(item => item.id);
  tableAlarmSelectedData.value = selection;
  selectIds.value = ids;
};

/** 多选框选中数据 */
const handleSelectionChange2 = (selection: any) => {
  console.log(selection);
  // tableAlarmSelectedData.value = selection;
};

// 查询所有报警
const queryAllAlarm = async val => {
  const params = { ...queryAlarmParams.value };
  params.pageNum = 1;
  params.pageSize = 9999; // 默认查询所有数据
  params[`${searchIdAlarm.value.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] =
    searchIdAlarm.value.indexOf("ROOM") === -1 ? [searchIdAlarm.value] : searchIdAlarm.value;
  if (val) {
    dateArr.value = initLineDate(lineWidth.value);
    const param1 = proxy.addDateRange(params, dateArr.value, "startTime", "endTime");
    // const param1 = proxy.addDateRange(params, ["", ""], "startTime", "endTime");
    const res: any = await queryAreaWornings(param1);
    // 初始化曲线--根据已选点位数据更新出曲线宽度对应的数据
    const chartsData = res.data.filter(item => selectIds.value.indexOf(item.id) !== -1);
    console.log("chartsData", chartsData);
    initLineChart(chartsData || []);
    // initLineChart(res.data || []);
  } else {
    const param2 = proxy.addDateRange(params, dateRangeAlarm.value, "startTime", "endTime");
    const data: any = await queryAreaWornings(param2);
    tableAlarmData.value = data?.data.slice(queryAlarmParams.value.pageNum - 1, queryAlarmParams.value.pageSize);
    tableAlarmDataAll.value = data?.data || [];
    tableAlarmSelectedData.value = [];
    clearTableSelection();
  }
};

// 合并同类项数组
const mergeDataByProperty = arr => {
  const merged = [];
  let propertyValues = {};
  const keyArr: any = Array.from(new Set(arr.map(item => item.point))) || [];
  for (const val in keyArr) {
    propertyValues[keyArr[val]] = [];
    console.log(val);
    arr.forEach(item => {
      if (item.point === keyArr[val]) {
        propertyValues[keyArr[val]].push({
          name: item.alarmTime,
          value: Number(item.realityValue)
        });
      }
    });
  }
  return propertyValues;
};

// 刷新曲线
const initLineChart = chartData => {
  console.log("chartData", chartData);
  let legendData = Array.from(new Set(chartData.map(item => item.point)));
  let mergeData = mergeDataByProperty(chartData);
  let featData = getAllSecondsData(dateArr.value[0], dateArr.value[1]);
  let seriesData = Object.keys(mergeData).map((item, index) => {
    let arr = [];
    // const hasValue = mergeData[item].map(e => e.name.split(" ")[1]);
    for (let itemX of featData) {
      let found = false;
      for (let itemY of mergeData[item]) {
        if (itemX.value === itemY.name.split(" ")[1]) {
          itemX.num = itemY.value;
          found = true;
          break;
        }
      }
      if (!found) {
        itemX.num = null;
      }
    }
    arr = featData.map(ele => ele.num);
    return {
      name: item,
      type: "line",
      emphasis: {
        focus: "series",
        blurScope: "coordinateSystem"
      },
      symbol: "circle", // 设置有数据的点显示为圆形标记
      symbolSize: 8,
      itemStyle: {
        borderWidth: 2 // 可以设置标记的边框粗细
      },
      showSymbol: true, // 显示标记
      lineStyle: {
        type: "dashed" // 可以设置没有数据连接时的线条样式为虚线
      },
      yAxisIndex: index,
      // itemStyle: {
      //   color: "#4786FF"
      // },
      data: arr
    };
  });
  let xData = featData.map(item => item.value);
  let yAxisData = legendData.map((item, index) => {
    return {
      type: "value",
      name: `℃-Y${index + 1}`,
      offset: (0 + index) * 50,
      alignTicks: true,
      splitNumber: 5,
      axisLine: {
        lineStyle: {
          width: 2
        }
      }
    };
  });
  // optionData.value = { legendData, xData, yAxisData, seriesData };
  console.log(xData, mergeData, legendData, yAxisData, seriesData, "55555555555555555");
  alarmOptions.value = {
    title: {
      text: "点位报警历史曲线",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "24px",
      top: "15%",
      right: `${yAxisData.length * 30}`,
      bottom: "5%",
      containLabel: true
    },
    xAxis: {
      // type: "category",
      data: xData
    },
    yAxis: yAxisData,
    series: seriesData
  };
};

// 获取秒的X轴间隔
function getAllSecondsData(startTime, endTime) {
  let currentTime = new Date(startTime);
  let endT = new Date(endTime);
  let secondsData = [];
  while (currentTime <= endT) {
    // 构建当前秒的数据，这里以对象的形式返回秒数和时间戳
    let hour = currentTime.getHours() < 10 ? "0" + currentTime.getHours().toString() : currentTime.getHours().toString();
    let minites = currentTime.getMinutes() < 10 ? "0" + currentTime.getMinutes().toString() : currentTime.getMinutes().toString();
    let seconds = currentTime.getSeconds() < 10 ? "0" + currentTime.getSeconds().toString() : currentTime.getSeconds().toString();
    let data = {
      value: hour + ":" + minites + ":" + seconds,
      timestamp: currentTime.getTime()
    };
    secondsData.push(data);
    // 将当前时间向前推进一秒
    currentTime.setSeconds(currentTime.getSeconds() + 1);
  }

  return secondsData;
}

// 点位曲线
const labelLayoutLineFn = async (ec: any) => {
  const title = "点位报警历史曲线";
  const param = {};
  const data = {};
  return labelLayoutFnLine(ec, data, title);
};

const labelLayoutFnLine = (ec: any, data: any, title: string) => {
  const { getWidth } = ec;
  // labelLine长度
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: UtilsEChartsOption = {
    title: {
      text: title,
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      data: ["WET", "ADF"],
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "24px",
      top: "15%",
      right: "24px",
      bottom: "5%",
      containLabel: true
    },
    xAxis: {
      // type: "category",
      data: ["12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: [
      {
        type: "value",
        name: `单位`,
        alignTicks: true,
        axisLine: {
          lineStyle: {
            width: 2
          }
        }
      }
    ],
    series: [
      {
        name: "WET",
        type: "line",
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#4786FF"
        },
        data: [111, 2, 4, 123, 456]
      },
      {
        name: "ADF",
        type: "line",
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#FFB266"
        },
        data: [21, 62, 24, 383, 126]
      }
    ]
  };
  return options;
};

// 重置Alarm列表
const resetAlarmTable = () => {
  dateRangeAlarm.value = [];
  const id = searchId.value;
  searchIdAlarm.value = id;
  queryAlarmParams.value = {
    pageNum: 1,
    pageSize: 10
  };
  queryAllAlarm(null);
};
// 重置Alarm列表
const resetAlarm = () => {
  lineBegin.value = proxy.parseTime(new Date(lineBegin.value).getTime() - 10 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}"); // 默认10分钟
  lineWidth.value = 10;
  // dateArr.value = [];
  dateArr.value = initLineDate(lineWidth.value);
  queryAllAlarm("flag");
};

const queryAlarmTable = (val: any) => {
  console.log(val);
  queryAlarmParams.value.pageNum = val.page;
  queryAlarmParams.value.pageSize = val.limit;
  const startIndex = (val.page - 1) * val.limit;
  const endIndex = startIndex + val.limit;
  tableAlarmData.value = tableAlarmDataAll.value.slice(startIndex, endIndex);
};

// 更新Y轴数量、系列、图例
const updateOption = (lengeds, yaxis, series) => {
  console.log(spcChartRef.value, chartsInstance, "spcChartRef.value");
  nextTick(() => {
    if (spcChartRef.value && chartsInstance) {
      chartsInstance.setOption(
        {
          title: {
            text: "曲线",
            textStyle: {
              fontSize: 16
            },
            // subtext: "曲线标题",
            left: "left",
            top: "top",
            padding: [10, 0, 0, 20]
          },
          tooltip: {
            trigger: "axis",
            confine: true
          },
          legend: {
            type: "scroll",
            pager: {
              orient: "vertical",
              pageButtonItemGap: 5
            },
            data: lengeds || [],
            orient: "horizontal",
            bottom: "0"
          },
          grid: {
            left: "10px",
            top: "70px",
            right: `${yaxis.length * 30}`,
            bottom: "30px",
            containLabel: true
          },
          xAxis: {
            // type: "category",
            data: xData.value || []
          },
          yAxis: yaxis || [],
          series: series || []
        },
        true
      );
      window.addEventListener("resize", handelResize);
    }
  });
};
// 编辑Y轴最大最小值
const updateYAxisLimits = el => {
  console.log(spcChartRef.value, chartsInstance, "spcChartRef.value");
  nextTick(() => {
    if (spcChartRef.value && chartsInstance) {
      chartsInstance.setOption({
        yAxis: pointsCurve.value.map((item: any) => {
          return {
            min: item.pointName === el.pointName ? el.spcForm.minY : item.spcForm.minY,
            max: item.pointName === el.pointName ? el.spcForm.maxY : item.spcForm.maxY
          };
        })
      });
      window.addEventListener("resize", handelResize);
    }
  });
};

// 编辑Y轴最大最小值
const updateYAxisLimits1 = el => {
  console.log(spcChartRefDom.value, chartsInstance1, "spcChartRefDom.value");
  nextTick(() => {
    if (spcChartRefDom.value && chartsInstance1) {
      chartsInstance1.setOption({
        yAxis: pointsCurve.value.map((item: any) => {
          return {
            min: item.pointName === el.pointName ? el.spcForm.minY : item.spcForm.minY,
            max: item.pointName === el.pointName ? el.spcForm.maxY : item.spcForm.maxY
          };
        })
      });
      window.addEventListener("resize", handelResize1);
    }
  });
};

const visible = ref(false);
const visibleY2 = ref(false);

const editSpcY = (el: any, index) => {
  updateYAxisLimits(el);
  updateYAxisLimits1(el);
  el.visible = false;
};
const editSpcY2 = () => {
  getWeatherData();
  visibleY2.value = false;
};

const addData = () => {
  // const data1 = yData1.value;
  // const data2 = yData2.value;
  // const data3 = yData3.value;
  // const data = xData.value;
  // data1.push(40);
  // data2.push(140);
  // data3.push(240);
  // data.push("2023-08-10");
  // yData1.value = data1;
  // yData2.value = data2;
  // yData3.value = data3;
  // xData.value = data;
  // initSpc();
  // window.addEventListener("resize", handelResize);
};

const handelResize = () => {
  if (chartsInstance) {
    chartsInstance.resize();
  }
};

const handelResize1 = () => {
  if (chartsInstance1) {
    chartsInstance1.resize();
  }
};

const setOption = (legendData, yAxis, xData, seriesData) => {
  return {
    title: {
      text: "曲线",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      pager: {
        orient: "vertical",
        pageButtonItemGap: 5
      },
      data: legendData || [],
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "10px",
      top: "70px",
      right: `${yAxis.length * 30}`,
      bottom: "30px",
      containLabel: true
    },
    xAxis: {
      // type: "category",
      data: xData || []
    },
    yAxis: yAxis || [],
    series: seriesData || []
  };
};

const initSpc = () => {
  console.log(pointsCurve.value, xData.value, yAxis.value, legendData.value, seriesData.value, "123123");
  chartsInstance = echarts.init(spcChartRef.value);
  const option = {
    title: {
      text: "曲线",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      pager: {
        orient: "vertical",
        pageButtonItemGap: 5
      },
      data: legendData.value || [],
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "10px",
      top: "70px",
      right: `${yAxis.value.length * 30}`,
      bottom: "30px",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xData.value || []
    },
    yAxis: yAxis.value || [],
    series: seriesData.value || []
  };
  if (spcChartRef.value && chartsInstance) {
    chartsInstance.setOption(option);
    window.addEventListener("resize", handelResize);
  }
};

window.addEventListener("resize", handelResize);

// 日期转化
const initDate = (val: number) => {
  const now = new Date();
  const utcTime = now.toISOString();
  const beijingTime = new Date(utcTime).getTime() + 8 * 60 * 60 * 1000;
  const start = beijingTime - val * 60 * 60 * 1000;
  const startTime = new Date(start).toISOString().slice(0, 19).replace("T", " ");
  const endTime = new Date(beijingTime).toISOString().slice(0, 19).replace("T", " ");
  return [startTime, endTime];
};

onMounted(async () => {
  initLineTime();
  console.log(dateArr.value, getAllSecondsData(dateArr.value[0], dateArr.value[1]), "55555555555555555");
  // dateRange.value = initDate(4);
  dateRangeSpc.value = initDate(4);
  const res: any = await queryChildByTypeCodeAndItemValue({
    typeCode: "OUTDOOR_WEATHER"
  });
  weatherSpcJobList.value = res;
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  getWeatherData();
  // 通过厂区字典查询区域
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  factoryList.value = JSON.parse(codes[1].itemDesc);
  // console.log(codes[1].itemDesc);
  const id = JSON.parse(codes[1].itemDesc)[0].facCode; // 暂时写死一期厂区
  await queryAreaList(id);
  await queryPointsList();
  queryTable();

  // 显示历史数据
  viewSpcDetail();
  // 初始化spc
  // initSpc();
});

onUnmounted(() => {
  window.removeEventListener("resize", handelResize);
});
</script>

<template>
  <div>
    <div class="details_box">
      <div class="top_turnback">
        <px-button type="primary" :icon="ArrowLeft" @click="turnBack">返回</px-button>
      </div>
      <div v-show="showAlarmDetail" class="alarm_detail">
        <px-form ref="queryAlarmRef" class="custom-form-ui-new" :model="queryAlarmParams" :inline="true" label-width="68px">
          <px-form-item label="名称" prop="point" style="width: 220px">
            <!-- <px-select v-model="queryAlarmParams.point" clearable placeholder="请选择名称">
              <px-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
            </px-select> -->
            <px-input v-model="queryAlarmParams.point" clearable placeholder="请输入名称" />
          </px-form-item>
          <px-form-item label="级别" prop="alarmLevel" style="width: 220px">
            <px-select v-model="queryAlarmParams.alarmLevel" clearable placeholder="请选择级别">
              <px-option v-for="item in filterList" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
          <px-form-item label="区域" prop="areaId" style="width: 220px">
            <px-select v-model="searchIdAlarm" placeholder="请选择区域" @change="handleAreaChange">
              <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
            </px-select>
          </px-form-item>
          <!-- <px-form-item label="房间" prop="areaId" style="width: 220px">
          <px-select v-model="queryAlarmParams.roomId" clearable placeholder="请选择房间">
            <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
          </px-select>
        </px-form-item> -->
          <px-form-item label="时间日期" style="width: 460px">
            <px-date-picker
              v-model="dateRangeAlarm"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </px-form-item>
          <px-form-item label="周期" prop="lifecycle" style="width: 220px">
            <px-select v-model="queryAlarmParams.lifecycle" clearable placeholder="请选择周期" @change="handleChangeAlarm">
              <px-option v-for="item in testCompanyList" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
          <px-form-item>
            <px-button type="primary" @click="queryAllAlarm(null)">查询</px-button>
            <px-button @click="resetAlarmTable">重置</px-button>
          </px-form-item>
        </px-form>
        <px-row :gutter="24">
          <px-col :span="16">
            <barTitle title="Alarm列表" />
            <px-table
              ref="tableRef"
              v-loading="loading"
              max-height="389"
              :header-cell-style="{ background: '#e7eefb', color: '#000' }"
              border
              :data="tableAlarmData"
              show-overflow-tooltip
              :row-key="row => row.id"
              @selection-change="handleSelectionChange"
            >
              <px-table-column type="selection" width="40" :reserve-selection="true" />
              <px-table-column label="时间" align="center" prop="alarmTime" width="160" />
              <px-table-column label="组" align="center" prop="factoryId" />
              <px-table-column label="名称" align="center" prop="point" />
              <px-table-column label="报警信息" align="center" prop="alarmContent" show-overflow-tooltip width="100" />
              <px-table-column label="级别" align="center" prop="alarmLevel" />
              <px-table-column label="当前值" align="center" prop="realityValue" />
              <px-table-column label="报警限" align="center" prop="settingValue" />
              <px-table-column label="状态" align="center" prop="alarmStatus" />
              <px-table-column label="报警持续时间" align="center" prop="alarmDurationTime" width="180" />
              <px-table-column label="未确认持续时间" align="center" prop="updateTime" width="160" />
            </px-table>

            <pagination
              v-show="tableAlarmDataAll && tableAlarmDataAll.length > 0"
              v-model:page="queryAlarmParams.pageNum"
              v-model:limit="queryAlarmParams.pageSize"
              :total="tableAlarmDataAll.length"
              @pagination="queryAlarmTable"
            />
          </px-col>
          <px-col :span="8">
            <barTitle title="已选" />
            <px-table
              v-loading="loading"
              max-height="444"
              :header-cell-style="{ background: '#e7eefb', color: '#000' }"
              border
              :data="tableAlarmSelectedData"
              show-overflow-tooltip
            >
              <px-table-column label="时间" align="center" prop="alarmTime" width="160" />
              <px-table-column label="组" align="center" prop="factoryId" />
              <px-table-column label="名称" align="center" prop="point" />
              <px-table-column label="报警信息" align="center" prop="alarmContent" show-overflow-tooltip width="100" />
              <px-table-column label="级别" align="center" prop="alarmLevel" />
              <px-table-column label="当前值" align="center" prop="realityValue" />
              <px-table-column label="报警限" align="center" prop="settingValue" />
              <px-table-column label="状态" align="center" prop="alarmStatus" />
              <px-table-column label="报警持续时间" align="center" prop="alarmDurationTime" width="180" />
              <px-table-column label="未确认持续时间" align="center" prop="updateTime" width="160" />
            </px-table>
          </px-col>
        </px-row>
        <div class="con_spc">
          <div class="left_form">
            <barTitle title="曲线设置" />
            <div class="left_text">曲线开始时间</div>
            <px-date-picker v-model="lineBegin" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择日期与时间" />
            <div class="left_text">曲线宽度</div>
            <px-select v-model="lineWidth" clearable placeholder="请选择曲线宽度" @change="handleChangeLine">
              <px-option v-for="item in minitesList" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
            <div class="left_btn">
              <px-button type="primary" plain @click="queryAllAlarm('flag')">刷新曲线</px-button>
              <px-button style="width: 88px" plain @click="resetAlarm">重置</px-button>
            </div>
          </div>
          <div class="spc_com">
            <!-- <div ref="spcChartRefDom" style="min-width: 400px; height: 552px" /> -->
            <lineChart ref="spcChartRefDom" :key="new Date().getTime()" :width="800" :options="alarmOptions" />
          </div>
        </div>
      </div>
      <div v-if="showSpcDetail" class="spc_detail">
        <div class="import-bottle-title">
          <px-icon color="#F59E0B"><WarningFilled /></px-icon>
          &nbsp;指标曲线请先设置SPC
          <span class="download" @click="gotoSpc"> 去设置 </span>
        </div>
        <px-form ref="querySpcDetailRef" :model="querySpcDetailParams" :inline="true" label-width="68px">
          <px-form-item label="指标类型" prop="alarmLevel">
            <px-checkbox-group v-model="spcJobList">
              <px-checkbox v-for="item in weatherSpcJobList" :key="item.id" :label="item.itemDesc">{{ item.itemName }}</px-checkbox>
              <!-- <px-checkbox label="weather.outdoor.temp.dry_1">室外干球温度</px-checkbox>
              <px-checkbox label="weather.outdoor.temp.wet_1">室外湿球温度</px-checkbox>
              <px-checkbox label="weather.outdoor.euthalpy_1">焓值</px-checkbox>
              <px-checkbox label="weather.outdoor.humidity_1">绝对湿度</px-checkbox>
              <px-checkbox label="weather.outdoor.temp.dew_1">露点</px-checkbox> -->
            </px-checkbox-group>
          </px-form-item>
          <px-form-item label="时间日期" style="width: 460px">
            <px-date-picker
              v-model="dateRangeSpcDetail"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </px-form-item>
          <px-form-item>
            <px-button type="primary" @click="querySpc">查询</px-button>
            <px-button @click="resetSpc">重置</px-button>
          </px-form-item>
        </px-form>
        <div class="con_spc">
          <div class="spc_com">
            <!-- <div ref="spcChartRef2" style="min-width: 400px; height: 552px" /> -->
            <lineChart ref="spcChartWeatherRef" :key="new Date().getTime()" :width="800" :options="weatherOptions" />
            <!-- <spcCharts ref="spcChartWeatherRef" :key="new Date().getTime()" :width="800" :optionData="weatherOptions" color="#ccc" /> -->
            <!-- <px-popover
              v-for="(item, index) in pointsCurve"
              :key="item.pointName"
              :visible="item.visible"
              placement="right-start"
              title="图表范围"
              :width="290"
            >
              <px-form :inline="true" :model="item.spcForm">
                <px-row>
                  <px-col :span="12">
                    <px-form-item label="最小值" style="width: 120px">
                      <px-input v-model="item.spcForm.minY" placeholder="请输入" clearable />
                    </px-form-item>
                  </px-col>
                  <px-col :span="12">
                    <px-form-item label="最大值" style="width: 120px">
                      <px-input v-model="item.spcForm.maxY" placeholder="请输入" clearable />
                    </px-form-item>
                  </px-col>
                </px-row>
              </px-form>
              <div style="margin: 0; text-align: right">
                <px-button size="small" text @click="item.visible = false">取消</px-button>
                <px-button size="small" type="primary" @click="editSpcY(item, index)">确定</px-button>
              </div>
              <template #reference>
                <px-icon
                  color="#3B82F6"
                  class="edit_y1"
                  :style="index === 0 ? { top: '0', left: '7' } : { top: '0', right: `${(pointsCurve.length - index) * 40 - 15}px` }"
                  @click="item.visible = true"
                  ><EditPen
                /></px-icon>
              </template>
            </px-popover> -->
          </div>
        </div>
        <barTitle title="数据明细" />
        <px-table v-loading="loading" max-height="389" :header-cell-style="{ background: '#e7eefb', color: '#000' }" border :data="dataDetailTable">
          <px-table-column label="时间" prop="startTime" />
          <px-table-column label="大气指标类型" prop="indicatorName" />
          <px-table-column label="值" prop="avgValue" />
        </px-table>

        <!-- <pagination
          v-show="tableAlarmDataAll && tableAlarmDataAll.length > 0"
          v-model:page="queryAlarmParams.pageNum"
          v-model:limit="queryAlarmParams.pageSize"
          :total="tableAlarmDataAll.length"
          @pagination="queryAlarmTable"
        /> -->
      </div>
    </div>
    <px-dialog v-model="contentVisible" title="批注历史" width="956" align-center>
      <px-table v-loading="hishoryLoading" class="digtable1" :data="contentList" height="250" show-overflow-tooltip border>
        <px-table-column label="时间" prop="createTime">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </px-table-column>
        <px-table-column label="批注人" prop="creator">
          <template #default="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </px-table-column>
        <px-table-column label="内容" prop="content">
          <template #default="scope">
            <span>{{ scope.row.content }}</span>
          </template>
        </px-table-column>

        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <pagination
        v-show="total2 > 0"
        v-model:page="queryParams2.pageNum"
        v-model:limit="queryParams2.pageSize"
        style="margin-bottom: -10px"
        :total="total2"
        @pagination="queryAlarmHistory"
      />
      <!-- <template #footer>
        <span class="dialog-footer">
          <px-button @click="progressVisible = false">取消</px-button>
          <px-button type="primary" @click="addRukudetails()"> 确认 </px-button>
        </span>
      </template> -->
    </px-dialog>
    <px-dialog v-model="contentTextVisible" title="批注" width="677" align-center>
      <px-row class="contentrow">
        <px-col :span="24">
          <px-input v-model="alarmRemake" style="margin-top: 16px" :rows="2" type="textarea" placeholder="请输入" />
        </px-col>
      </px-row>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="contentTextVisible = false">取消</px-button>
          <px-button type="primary" @click="addcontent()"> 保存 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<style lang="scss" scoped>
.top_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  min-width: 1300px;
  height: 105px;
  padding: 16px 24px;
  background-color: white;
  border-radius: 4px;

  .time_date {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding-right: 83px;
    font-weight: 500;
    border-right: 1px solid #dcdcdc;

    .time {
      height: 44px;
      margin-bottom: 8px;
      font-size: 44px;
      line-height: 44px;
      color: #13c2c2;
    }

    .date {
      height: 20px;
      font-size: 14px;
      line-height: 20px;
      color: #7997a8;
    }
  }

  .right_btn {
    display: flex;
    align-items: center;
    justify-content: center;

    .btn_item {
      margin-bottom: 8px;
    }
  }
}

.mid_box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
  min-width: 1300px;
  height: 693px;
  padding: 16px 24px;
  margin-top: 16px;
  background-color: white;
  border-radius: 4px;

  .switch_tabs {
    display: flex;
    flex-flow: row nowrap;
    gap: 12px;
    align-items: center;
    justify-content: flex-start;

    .switch_item {
      font-size: 14px;
      text-align: center;
      cursor: pointer;
      border: 1px solid #dcdcdc;
      border-radius: 3px;

      &:hover {
        border: 1px solid #3b82f6;
      }
    }

    .activeClass {
      position: relative;
      font-size: 14px;
      text-align: center;
      cursor: pointer;
      border: 1px solid #3b82f6;
      border-radius: 3px;

      &::after {
        position: absolute;
        top: 42px;
        left: 50%;
        width: 0;
        height: 0;
        content: "";
        border: 8px solid transparent;
        border-top-color: #3b82f6;
        transform: translate(-50%);
      }
    }

    .item_name {
      padding: 0 7px;
      white-space: nowrap;
      border-radius: 3px 3px 0 0;
    }

    .item_red {
      color: #fff;
      background-color: #ef4444;
      border-radius: 0 0 2px 2px;
    }

    .item_green {
      color: #fff;
      background-color: #10b981;
      border-radius: 0 0 2px 2px;
    }
  }

  .switch_con {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    height: 693px;

    .con_img {
      position: relative;
      // width: 100%;
      width: 600px;
      // height: 100%;
      height: 600px;
      // background-image: url("@/assets/svg/machine/build_img.png");
      background-repeat: no-repeat;
      background-position: center center;
      background-size: 100% 100%;

      .con_img_point {
        position: absolute;
        width: 42px;
        height: 57px;
        cursor: pointer;
        background-image: url("@/assets/svg/machine/warning.png");

        .point_item {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          content: "";
        }

        .pop_text {
          font-size: 16px;
          font-weight: 600;
        }
      }
    }

    .con_query {
      flex: 1;
      width: calc(100% - 731px);
      margin-left: 25px;

      .inspection-form {
        display: flex;
        flex-flow: row nowrap;
      }

      .con_spc {
        display: flex;
        justify-content: space-between;
        margin-top: 16px;

        .spc_com {
          position: relative;
          flex: 1;

          .edit_form {
            display: flex;
            flex-flow: row nowrap;
            gap: 10px;
          }

          .edit_y1 {
            position: absolute;
            cursor: pointer;
          }
        }

        .scroll_checkbox {
          width: 280px;
          height: 552px;
          margin-left: 8px;

          .point_name {
            font-size: 12px;
          }

          .area_item {
            margin-bottom: 8px;
            font-size: 14px;
            border: 1px solid #dcdcdc;
            border-radius: 3px;

            .area_top {
              display: flex;
              justify-content: space-between;
              height: 36px;
              padding: 0 16px;
              line-height: 36px;
              white-space: nowrap;
              border-radius: 3px 3px 0 0;
            }

            .area_bottom {
              display: flex;
              align-items: center;
              justify-content: space-between;
              height: 36px;
              padding: 5px 16px;
              line-height: 1;
              border-radius: 0 0 2px 2px;

              .bottom_item {
                flex: 1;
                text-align: center;
                border-right: 1px solid #909399;
              }

              .bottom_item:last-child {
                border-right: none;
              }

              .item_num {
                line-height: 26px;
              }

              .item_text {
                display: flex;
                flex-direction: column;
                gap: 2px;
                justify-content: space-between;

                .text {
                  font-size: 12px;
                  color: #909399;
                }

                .num {
                  font-size: 12px;
                }
              }
            }
          }
        }
      }
    }
  }

  .custom-form-ui .px-form-item {
    margin-bottom: 0;
  }
}

.btn_table {
  width: 100%;
  min-width: 1300px;
  padding: 16px 24px;
  margin-top: 16px;
  background-color: white;
  border-radius: 4px;

  .custom-form-ui-new {
    margin-top: 8px;
  }
}

.icon {
  cursor: pointer;
}

.details_box {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;

  .alarm_detail {
    width: 100%;
    min-width: 1300px;

    .con_spc {
      display: flex;
      justify-content: space-between;
      margin-top: 16px;

      .spc_com {
        position: relative;
        flex: 1;

        .edit_form {
          display: flex;
          flex-flow: row nowrap;
          gap: 10px;
        }

        .edit_y1 {
          position: absolute;
          cursor: pointer;
        }
      }

      .left_form {
        margin-right: 16px;

        .left_text {
          margin: 16px 0 8px;
          font-size: 14px;
          color: rgb(0 0 0 / 80%);
        }

        .left_btn {
          margin-top: 16px;
        }
      }
    }

    .custom-form-ui-new {
      margin-top: 16px;
      margin-bottom: 0;
    }
  }

  .spc_detail {
    width: 100%;
    min-width: 1300px;

    .con_spc {
      display: flex;
      justify-content: space-between;
      margin-top: 16px;

      .spc_com {
        position: relative;
        flex: 1;

        .edit_form {
          display: flex;
          flex-flow: row nowrap;
          gap: 10px;
        }

        .edit_y1 {
          position: absolute;
          cursor: pointer;
        }
      }
    }

    .import-bottle-title {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      width: 100%;
      height: 40px;
      padding-left: 16px;
      margin: 16px 0;
      line-height: 1;
      color: #333;
      background-color: #fef5e6;
      border: 1px solid #f7b648;
      border-radius: 6px;

      .download {
        margin-left: 8px;
        color: #3b82f6;
        cursor: pointer;
      }
    }
  }
}
</style>
